import uuid
import datetime
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy import Column, String, DateTime, Integer, Text
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


def generate_uuid():
    return uuid.uuid4().hex


class Alert(Base):
    """告警配置"""
    __tablename__ = 'alert'
    id = Column(String, primary_key=True, default=generate_uuid, comment='告警配置ID')

    name = Column(String, nullable=False, comment='告警配置名')
    type = Column(String, nullable=False, comment='告警类型')
    query = Column(JSONB, default={}, comment='搜索 数据源 + 搜索条件')
    triggers = Column(JSONB, default=[], comment='触发告警规则清单')
    cron = Column(JSONB, nullable=True, comment='告警周期')

    suppression = Column(JSONB, nullable=True, comment='抑制规则')
    alert_template = Column(Text, nullable=False, comment='告警文本 Jinja2模板')
    notifies = Column(JSONB, default=[], comment='告警通知列表 redis记录 notify使用者 alert:_xxx')

    created_at = Column(DateTime, default=datetime.datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='更新时间')
    statistic = relationship('AlertStatistic', cascade='all, delete', lazy='dynamic')


class AlertStatistic(Base):
    """告警 状态统计
    详细历史告警信息存储到es中 仪表盘去展示告警趋势
    """
    __tablename__ = 'alert_statistic'
    id = Column(String, primary_key=True, default=generate_uuid, comment='告警配置ID')

    execute_count = Column(Integer, default=0, comment='执行次数')
    alert_count = Column(Integer, default=0, comment='告警次数')
    started_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='任务执行时间')
    alerted_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='最近告警时间')
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='更新时间')
